package com.gmrz.uap.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;

import com.gmrz.uap.cache.AmmsCacheUtil;
import com.gmrz.uap.cache.CacheStoreService;
import com.gmrz.uap.cache.CacheStoreServiceEhcacheImpl;
import com.gmrz.uap.model.User;
import com.gmrz.uap.uasconfig.UasConfigConst;
import com.gmrz.uap.uasconfig.UasConfigContentService;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UAPSSOHelper {

    public static final String UAP_SESSION_ID = "UAPSESSIONID";
    public static final String LOGIN_WRONG_COUNT = "LOGINWRONGCOUNT";
    public static final int UAP_SESSION_EXPIRE = 1800;
    public static final String UAP_SESSION_LOCALE_CACHE = "UAP_SESSION_LOCALE_CACHE";


    /**
     * 从COOKIE中取出UAPSESSIONID内容，根据内容从缓存中获取用户信息
     *
     * @param request
     * @return
     */
    public static User getUserByUapSessionId(HttpServletRequest request) {

        CacheStoreService cacheStoreService = UAPSSOHelper.getCacheStoreServiceForSession();

        Cookie cookie = findCookieByName(request, UAPSSOHelper.UAP_SESSION_ID);
        String ssoUser = cacheStoreService.getStr(cookie.getValue());
        User user = JSON.parseObject(ssoUser, new TypeReference<User>() {
        });

        return user;
    }

    /**
     * 将用户信息保存到缓存中
     *
     * @param request
     * @param user
     */
    public static void setUserIntoCache(HttpServletRequest request, User user) {
        CacheStoreService cacheStoreService = UAPSSOHelper.getCacheStoreServiceForSession();

        Cookie cookie = findCookieByName(request, UAPSSOHelper.UAP_SESSION_ID);
        cacheStoreService.set(cookie.getValue(), JSONObject.toJSONString(user));
    }

    public static void setUserIntoCache(HttpServletRequest request, User user, int expire) {

        CacheStoreService cacheStoreService = UAPSSOHelper.getCacheStoreServiceForSession();

        Cookie cookie = findCookieByName(request, UAPSSOHelper.UAP_SESSION_ID);
        cacheStoreService.set(cookie.getValue(), JSONObject.toJSONString(user), expire);
    }


    /**
     * 从缓存中删除用户信息
     *
     * @param request
     */
    public static void removeUserFromCache(HttpServletRequest request) {

        CacheStoreService cacheStoreService = UAPSSOHelper.getCacheStoreServiceForSession();

        Cookie cookie = findCookieByName(request, UAPSSOHelper.UAP_SESSION_ID);
        cacheStoreService.remove(cookie.getValue());
    }

    /**
     * 根据缓存中的缓存实现类信息返回缓存连接的实现
     *
     * @return CacheStoreService
     */
    public static CacheStoreService getCacheStoreServiceForSession() {

        String cacheStoreClass = UasConfigContentService.me.getUasConfigValueStr(UasConfigConst.UAFCHALLENGESTORECLASSNAME);

        CacheStoreService cacheStoreService;
        if (cacheStoreClass.contains(AmmsCacheUtil.CHALLENGESTORESERVICEDEFAULTIMPL)) {
            cacheStoreService = new CacheStoreServiceEhcacheImpl(UAP_SESSION_LOCALE_CACHE);
        } else {
            cacheStoreService = AmmsCacheUtil.getCacheStoreService();
        }

        return cacheStoreService;
    }



    public static Cookie findCookieByName(HttpServletRequest request, String cookieName) {
        Cookie[] cookies = request.getCookies();
        if(cookies == null) {
            return null;
        } else {
            for(int i = 0; i < cookies.length; ++i) {
                if(cookies[i].getName().equals(cookieName)) {
                    return cookies[i];
                }
            }

            return null;
        }
    }


    public static void addHttpOnlyCookie(HttpServletResponse response, Cookie cookie) {
        if(cookie != null) {
            String cookieName = cookie.getName();
            String cookieValue = cookie.getValue();
            int maxAge = cookie.getMaxAge();
            String path = cookie.getPath();
            String domain = cookie.getDomain();
            boolean isSecure = cookie.getSecure();
            StringBuffer sf = new StringBuffer();
            sf.append(cookieName + "=" + cookieValue + ";");
            if(maxAge >= 0) {
                sf.append("Max-Age=" + cookie.getMaxAge() + ";");
            }

            if(domain != null) {
                sf.append("domain=" + domain + ";");
            }

            if(path != null) {
                sf.append("path=" + path + ";");
            }

            if(isSecure) {
                sf.append("secure;HTTPOnly;");
            } else {
                sf.append("HTTPOnly;");
            }

            response.addHeader("Set-Cookie", sf.toString());
        }
    }
}
